class Solution:
    def sumOfDistancesInTree(self, N: int, edges: list) -> list:
        def dfs(node, pre, ans, count):
            for i in adj[node]:
                if i == pre:
                    continue
                dfs(i, node, ans, count)
                count[node] += count[i]
                ans[node] += (ans[i] + count[i])

        def dfs2(node, pre, ans, count):
            for i in adj[node]:
                if i == pre:
                    continue
                ans[i] = ans[node] - count[i] + N - count[i]
                dfs2(i, node, ans, count)

        ans = [0 for _ in range(N)]
        count = [1 for _ in range(N)]
        adj = [[] for _ in range(N)]
        for (x, y) in edges:
            adj[x] += [y]
            adj[y] += [x]
        dfs(0, -1, ans, count)
        dfs2(0, -1, ans, count)

        return ans
